﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using System.IO;
using System.Data;
using System.Drawing;
using System.Security.Cryptography;

namespace DreamsI.EduSpon
{
    public class eduSponCommon : System.Web.UI.Page, IDisposable
    {
        #region 암호화 관련
        /// <summary>
        /// Encrpyts the sourceString, returns this result as an Aes encrpyted, BASE64 encoded string
        /// </summary>
        /// <param name="plainSourceStringToEncrypt">a plain, Framework string (ASCII, null terminated)</param>
        /// <param name="passPhrase">The pass phrase.</param>
        /// <returns>
        /// returns an Aes encrypted, BASE64 encoded string
        /// </returns>
        public static string EncryptString(string plainSourceStringToEncrypt, string passPhrase)
        {
            try
            {

                //Set up the encryption objects
                using (AesCryptoServiceProvider acsp = GetProvider(Encoding.Default.GetBytes(passPhrase)))
                {
                    byte[] sourceBytes = Encoding.UTF8.GetBytes(plainSourceStringToEncrypt);
                    ICryptoTransform ictE = acsp.CreateEncryptor();

                    //Set up stream to contain the encryption
                    MemoryStream msS = new MemoryStream();

                    //Perform the encrpytion, storing output into the stream
                    CryptoStream csS = new CryptoStream(msS, ictE, CryptoStreamMode.Write);
                    csS.Write(sourceBytes, 0, sourceBytes.Length);
                    csS.FlushFinalBlock();

                    //sourceBytes are now encrypted as an array of secure bytes
                    byte[] encryptedBytes = msS.ToArray(); //.ToArray() is important, don't mess with the buffer

                    //return the encrypted bytes as a BASE64 encoded string
                    //return Convert.ToBase64String(encryptedBytes);
                    return Convert.ToBase64String(encryptedBytes);
                    //return Encoding.ASCII.GetString(encryptedBytes);

                }
            }
            catch (Exception ex)
            {
                return ex.ToString();
            }
        }


        /// <summary>
        /// Decrypts a BASE64 encoded string of encrypted data, returns a plain string
        /// </summary>
        /// <param name="base64StringToDecrypt">an Aes encrypted AND base64 encoded string</param>
        /// <param name="passphrase">The passphrase.</param>
        /// <returns>returns a plain string</returns>
        public static string DecryptString(string base64StringToDecrypt, string passphrase)
        {
            try
            {

                //Set up the encryption objects
                using (AesCryptoServiceProvider acsp = GetProvider(Encoding.Default.GetBytes(passphrase)))
                {
                    byte[] RawBytes = Convert.FromBase64String(base64StringToDecrypt);
                    //byte[] RawBytes = Encoding.ASCII.GetBytes(base64StringToDecrypt);

                    ICryptoTransform ictD = acsp.CreateDecryptor();

                    //RawBytes now contains original byte array, still in Encrypted state

                    //Decrypt into stream
                    MemoryStream msD = new MemoryStream(RawBytes, 0, RawBytes.Length);
                    CryptoStream csD = new CryptoStream(msD, ictD, CryptoStreamMode.Read);
                    //csD now contains original byte array, fully decrypted

                    //return the content of msD as a regular string
                    return (new StreamReader(csD)).ReadToEnd();
                }
            }
            catch (Exception ex)
            {
                return ex.ToString();
            }
        }

        private static AesCryptoServiceProvider GetProvider(byte[] key)
        {
            AesCryptoServiceProvider result = new AesCryptoServiceProvider();
            result.BlockSize = 128;
            result.KeySize = 256;
            result.Mode = CipherMode.CBC;
            result.Padding = PaddingMode.PKCS7;


            result.GenerateIV();
            //result.IV = new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
            result.IV = new byte[] { 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48 };
            //result.IV = new byte[] { 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0 };

            byte[] RealKey = GetKey(key, result);
            //result.Key = RealKey;
            result.Key = key;
            //result.Key = new byte[] {1,2,3,4,5,6,7,8,9,1,1,2,3,4,5,6};
            //result.IV = RealKey;
            return result;
        }

        private static byte[] GetKey(byte[] suggestedKey, SymmetricAlgorithm p)
        {
            byte[] kRaw = suggestedKey;
            List<byte> kList = new List<byte>();

            for (int i = 0; i < p.LegalKeySizes[0].MinSize; i += 8)
            {
                kList.Add(kRaw[(i / 4) % kRaw.Length]);
            }
            byte[] k = kList.ToArray();
            return k;
        }


        public string RijndaelManagedString(string text, string flag)
        {
            string sResult = "";

            string key = "12345678911234561234567891123456";
            string secret = text;

            if (secret != "" && secret != null)
            {
                secret = secret.Replace('*', '+');
                if (flag == "e")
                {
                    sResult = EncryptString(secret, key);
                    sResult = sResult.Replace('+', '*');

                }
                else
                {
                    sResult = DecryptString(secret, key);

                }
            }

            return sResult;
        }

        #endregion

        #region 이미지 처리


        /// <summary>
        /// 이미지 생성
        /// </summary>
        /// <param name="sSavePath">기본이미지 저장 경로</param>
        /// <param name="sThumbnailFilePath">썸네일 이미지 저장 경로</param>
        /// <param name="myfile"></param>
        /// <returns></returns>
        public bool SetImage(string sSavePath, string sThumbnailFilePath, HttpPostedFile myfile)
        {

            //이미지 처리 결과값
            bool bResult = false;

            string sThumbExtension;

           
            int intThumbWidth = 120;
            int intThumbHeight = 120;


            //이미지 파일 크기
            int nFileLen = myfile.ContentLength;

            byte[] myData = new byte[nFileLen];
            myfile.InputStream.Read(myData, 0, nFileLen);

            string sFilename = System.IO.Path.GetFileName(myfile.FileName);

            try
            {

                //이미지 파일 읽기
                int file_append = 0;
                System.IO.FileStream newFile = new System.IO.FileStream(Server.MapPath(sSavePath + sFilename), System.IO.FileMode.Create);
                newFile.Write(myData, 0, myData.Length);
                newFile.Close();

                //이미지 생성
                Bitmap myBitmap;

                System.Drawing.Image.GetThumbnailImageAbort myCallBack = new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback);
                

                myBitmap = new Bitmap(Server.MapPath(sSavePath + sFilename));
                file_append = 0;
                string sThumbFile = "s_" + System.IO.Path.GetFileNameWithoutExtension(myfile.FileName) + ".jpg";

                //썸네일 이미지 생성
                System.Drawing.Image myThumbnail = myBitmap.GetThumbnailImage(intThumbWidth, intThumbHeight, myCallBack, IntPtr.Zero);
                //Response.Write("sthumbnailFilePath - Server.MapPath : " + Server.MapPath(sThumbnailFilePath + sFilename));
                myThumbnail.Save(Server.MapPath(sThumbnailFilePath + sThumbFile));

                myThumbnail.Dispose();
                myBitmap.Dispose();


            }
            catch (Exception ex)
            {
                bResult = false;

                Response.Write("SetImage : " + ex.ToString());
            }

            return bResult;

        }


        public bool ThumbnailCallback()
        {
            return false;
        }
        
        #endregion
        
        #region 파일처리 관련

        

        #endregion
    }
}